package org.scohen.juploadr.uploadapi.flickrrest.transform;

import java.util.SortedMap;
import java.util.TreeMap;

import org.scohen.juploadr.app.UploadImage;
import org.scohen.juploadr.uploadapi.CommunicationException;
import org.scohen.juploadr.uploadapi.ProtocolException;
import org.scohen.juploadr.uploadapi.flickrrest.DefaultFlickrHandler;
import org.scohen.juploadr.uploadapi.flickrrest.FlickrMethod;
import org.scohen.juploadr.uploadapi.flickrrest.PhotoNotFoundException;
import org.scohen.juploadr.uploadapi.flickrrest.PostUploadAction;
import org.scohen.juploadr.uploadapi.flickrrest.RestFlickrApi;

public class Rotate extends FlickrMethod implements PostUploadAction {
    private String photoId;
    private int degrees;
    private UploadImage image;

    public Rotate(UploadImage img) {
        this.photoId = img.getPhotoId();
        this.degrees = img.getRotation() % 360;
        this.image = img;
    }

    public DefaultFlickrHandler getResponseHandler() {
        return new NullFlickrHandler(this);
    }

    public SortedMap<String, String> getParams() {
        TreeMap<String, String> params = new TreeMap<String, String>();
        params.put("api_key", RestFlickrApi.FLICKR_API_KEY);
        params.put("method", "flickr.photos.transform.rotate");
        params.put("photo_id", photoId);
        params.put("degrees", String.valueOf(degrees));
        return params;
    }

    public boolean isAuthorized() {
        return true;
    }

    public boolean execute() throws ProtocolException, CommunicationException {
        if (degrees != 0) {
            return super.execute();
        } else {
            return true;
        }
    }

    private class NullFlickrHandler extends DefaultFlickrHandler {

        public NullFlickrHandler(Object parent) {
            super(parent);
        }
    }

    public UploadImage getImage() {
        return image;
    }

    public String getErrorText() {
        return "rotate " + image.getTitle();
    }

    @Override
    protected ProtocolException buildProtocolException(int errorCode) {
        switch (errorCode) {
        case 1:
            return new PhotoNotFoundException();
        case 2:
            return new InvalidRotationException();
        case 3:
            return new TemporaryFailureException();
        case 4:
            return new RotationServiceDisabledException();
        default:
            return null;
        }

    }

}
